package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.omg.CORBA.portable.ApplicationException;

import dataContracts.CommandParser;
import dataContracts.CommandType;

class SendFileHandler implements Runnable {
	ClientConnection client;
	ServerProgram server;
	String fileName;
	String directoryPath;
	// HACK: 0 means download, 1 means upload
	public short operation = 0;
	
	SendFileHandler(ClientConnection client, ServerProgram server, String directoryPath, String fileName) {
		this.server = server;
		this.client = client;
		this.fileName = fileName;
		this.directoryPath = directoryPath; 
	}
	
	@Override
	public void run() {
		DownloadServer ds = null;
		try {
			ds = setupServerOnOpenPort();
			// send back the filename and port so the client can download
			CommandType commandType = (operation == 0) ? CommandType.RecvFile : CommandType.GetFile;
			String cmd = CommandParser.buildCommand(commandType, fileName + ":" + ds.port);
			client.command(cmd);
			
			// send the download to the client
			ds.run();
		} catch (ApplicationException ex) {
			// notify the client that it needs to try again later...
			client.command(CommandParser.buildCommand(CommandType.Broadcast, ex.getMessage()));
		}
	}
	
	private DownloadServer setupServerOnOpenPort() throws ApplicationException {
		//start with the server port and move up
		int port = server.portNumber+1, maxClients = 10;
		DownloadServer ds;
		
		while (port < server.portNumber + maxClients) {
			try {
				ds = new DownloadServer(fileName, port);
				// if no exception was thrown, the port is available
				ds.operation = operation;
				return ds;
			} catch (IOException e) {
				// couldn't connect, try the next port
				port++;
			}
		}
		
		// if we get here, it means we could not find an open port... 
		throw new ApplicationException("There are too many clients downloading, try again shortly...", null);
	}
}